//
//  FSScrollContentViewController.m
//  FSScrollViewNestTableViewDemo
//
//  Created by huim on 2017/5/23.
//  Copyright © 2017年 fengshun. All rights reserved.
//

#import "HHScrollContentViewController.h"
#import "ShoppingHotContentTableViewCell.h"
#import "SupportCategoryGoodListModel.h"
#import "PopupWebView.h"
#import <AudioToolbox/AudioToolbox.h>
#import "WouldLikeView.h"

@interface HHScrollContentViewController ()<UITableViewDataSource, UITableViewDelegate>
{
    SystemSoundID scoreClickBtnID;   // 自己设置的音效 (系统的振动音效 - kSystemSoundID_Vibrate)
}
@property (nonatomic, assign) BOOL fingerIsTouch;

@property (nonatomic, strong) NSMutableArray *dataMutArray;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, copy) NSString *classId;
@property (nonatomic, copy) NSString *sortId;

@end

@implementation HHScrollContentViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"---%@",self.title);
//    WouldLikeView *likeViewop = [[WouldLikeView alloc] init];
}

- (NSMutableArray *)dataMutArray {
    if (!_dataMutArray) {
        _dataMutArray = [[NSMutableArray alloc] init];
    }
    return _dataMutArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = Colorf2f2f2;
    [self setupSubViews];
    [self loadDataWithClassId:@"0" SortId:@"1" IsUp:YES];
    self.page = 1;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"5a2e388b2886c.wav" ofType:@""]]), &scoreClickBtnID);
}

- (void)loadDataWithClassId:(NSString *)classId SortId:(NSString *)sortId IsUp:(BOOL)isUp{
    self.classId = classId;
    self.sortId = sortId;
    if (isUp) {
        self.page = 1;
    }
    WS(weakSelf);
    [SupportCategoryGoodListModel supprotGoodListWithPage:self.page andClassID:classId SortId:sortId successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 1) {
            if (isUp) {
                [weakSelf.dataMutArray removeAllObjects];
            }
            NSArray *array = responseObject[@"data"];
            for (int i = 0 ; i < array.count; i ++) {
                SupportCategoryGoodListModel *model = [SupportCategoryGoodListModel mj_objectWithKeyValues:array[i]];
                [weakSelf.dataMutArray addObject:model];
            }
            [weakSelf.tableView reloadData];
        } else if([responseObject[@"code"] intValue] == 2 && weakSelf.page == 1){
            [weakSelf.dataMutArray removeAllObjects];
            [weakSelf.tableView reloadData];
        }
        [weakSelf.tableView.mj_footer endRefreshing];
    } failBlock:^(NSError *error) {
    }];
}


- (void)setupSubViews
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(Margin, 0, CGRectGetWidth(self.view.bounds)-2*Margin, HEIGHT-Height_TabBar-Height_StatusBar-jisuan(60)-50) style:UITableViewStylePlain];
    _tableView.backgroundColor = Colorf2f2f2;
    [_tableView registerClass:[ShoppingHotContentTableViewCell class] forCellReuseIdentifier:@"ShoppingHotContentTableViewCell"];
    [_tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = jisuan(205);
    [self.view addSubview:_tableView];
    WS(weakSelf);
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf loadDataWithClassId:self.classId SortId:self.sortId IsUp:NO];
    }];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在加载。。。。" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多数据！" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = Font(17);
    footer.stateLabel.textColor = Color999999;
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = NO;

}





#pragma mark Setter
- (void)setIsRefresh:(BOOL)isRefresh
{
    _isRefresh = isRefresh;
}

#pragma mark UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataMutArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShoppingHotContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShoppingHotContentTableViewCell"];
    cell.type = 1;
    cell.model = self.dataMutArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static BOOL shouldPrevent;
    if (shouldPrevent) return;
    shouldPrevent = YES;
    
    PopupWebView *popppview = [[PopupWebView alloc] init];
    popppview.hidden = YES;
    popppview.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    [[UIApplication sharedApplication].keyWindow addSubview:popppview];
    
    WS(weakSelf);
    SupportCategoryGoodListModel *model = self.dataMutArray[indexPath.row];
    if ([CommonUserInfo sharedInstance].isLogin) {
        NSString *string = [NSString stringWithFormat:@"{\"user_id\" : \"%@\"}",[RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey]];
        [PPNetworkHelper POST:@"welfare/browse/index" parameters:@{@"json":string} success:^(id responseObject) {
            if ([responseObject[@"code"] intValue] == 1) {
                [popppview loadWithHtml:responseObject[@"data"][@"jiangli"]];
                popppview.hidden = NO;
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                AudioServicesPlaySystemSound(self->scoreClickBtnID);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
                    [popppview removeFromSuperview];
                    ShoppingGoodsContentViewController *ctr = [[ShoppingGoodsContentViewController alloc] init];
                    ctr.goodID = model.goodId;
                    [weakSelf.navigationController pushViewController:ctr animated:YES];
                    shouldPrevent = NO;
                });
            } else {
                shouldPrevent = NO;
                ShoppingGoodsContentViewController *ctr = [[ShoppingGoodsContentViewController alloc] init];
                ctr.goodID = model.goodId;
                [weakSelf.navigationController pushViewController:ctr animated:YES];
            }
        } failure:^(NSError *error) {
            shouldPrevent = NO;
            ShoppingGoodsContentViewController *ctr = [[ShoppingGoodsContentViewController alloc] init];
            ctr.goodID = model.goodId;
            [weakSelf.navigationController pushViewController:ctr animated:YES];
        }];
    } else {
        shouldPrevent = NO;
        ShoppingGoodsContentViewController *ctr = [[ShoppingGoodsContentViewController alloc] init];
        ctr.goodID = model.goodId;
        [self.navigationController pushViewController:ctr animated:YES];
    }
   
}

#pragma mark UIScrollView
//判断屏幕触碰状态
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
//    DebugLog(@"接触屏幕");
    self.fingerIsTouch = YES;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    self.fingerIsTouch = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!self.vcCanScroll) {
        scrollView.contentOffset = CGPointZero;
    }
    if (scrollView.contentOffset.y <= 0) {
//        if (!self.fingerIsTouch) {//这里的作用是在手指离开屏幕后也不让显示主视图，具体可以自己看看效果
//            return;
//        }
        self.vcCanScroll = NO;
        scrollView.contentOffset = CGPointZero;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"leaveTopqqqqq" object:nil];//到顶通知父视图改变状态
    }
}

#pragma mark LazyLoad


@end
